<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <BasicTable @register="registerTable" v-if="!isView">
      <template #toolbar>
        <a-button type="primary" @click="handleCheck"> 盘点 </a-button>
        <a-button type="primary" @click="handleHistory"> 历史明细 </a-button>
        <a-button type="primary" @click="handleScrap"> 报废 </a-button>
        <a-button type="primary" @click="handleCreate"> {{ t('新增') }} </a-button>
        <a-button type="primary" @click="handleImport"> {{ t('导入') }} </a-button>
        <a-button type="primary" @click="handleExport"> {{ t('导出') }} </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'state'">
          <a-switch v-model:checked="record.state" :checkedValue="1" :unCheckedValue="0" disabled />
        </template>
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:eye-outlined',
                onClick: handleView.bind(null, record),
              },
              {
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <MaterialInfo :id="recordId" @return-page="isView = false" v-else />
    <MaterialModal @register="registerModal" @success="reload" />
    <StockModal @register="registerStockModal" @success="handleReload" />
    <HistoryModal @register="registerHistoryModal" @success="handleReload" />
    <ImportModal
      @register="registerImportModal"
      importUrl="/caseErpMaterial/caseErpMaterial/import"
      @success="reload"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import {
    getMaterialPageList,
    deleteMaterialList,
    exportInfo,
    downloadTemplate,
  } from '/@/api/erp/material/list';
  import { getPropertylList } from '/@/api/erp/material/property';
  import { getCategoryList } from '/@/api/erp/material/category';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { ImportModal } from '/@/components/Import';
  import { downloadByData } from '/@/utils/file/download';
  import MaterialModal from './components/MaterialModal.vue';
  import MaterialInfo from './components/MaterialInfo.vue';
  import StockModal from './components/StockModal.vue';
  import HistoryModal from './components/HistoryModal.vue';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '物料编码',
      dataIndex: 'code',
      sorter: true,
    },
    {
      title: '物料名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '规格型号',
      dataIndex: 'model',
      sorter: true,
    },
    {
      title: '当前库存',
      dataIndex: 'inventory',
      sorter: true,
    },
    {
      title: '单位',
      dataIndex: 'unitName',
      sorter: true,
    },
    {
      title: '物料类别',
      dataIndex: 'typeName',
      sorter: true,
    },
    {
      title: '物料属性',
      dataIndex: 'propertyName',
      sorter: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      sorter: true,
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '物料名称',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入物料名称',
      },
    },
    {
      field: 'classesId',
      label: '物料类别',
      component: 'ApiSelect',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请选择物料类别',
        api: getCategoryList,
        labelField: 'typeName',
        valueField: 'id',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'propertyId',
      label: '物料属性',
      component: 'ApiSelect',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请选择物料属性',
        api: getPropertylList,
        labelField: 'propertyName',
        valueField: 'id',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'state',
      label: '状态',
      component: 'Select',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请选择状态',
        options: [
          { label: '启用', value: 1 },
          { label: '未启用', value: 0 },
        ],
        getPopupContainer: () => document.body,
      },
    },
  ];

  const { notification } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerStockModal, { openModal: openStockModal }] = useModal();
  const [registerHistoryModal, { openModal: openHistoryModal }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();

  const isView = ref(false);
  const recordId = ref('');
  const customRow = (record) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...getSelectRowKeys()];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        setSelectedRowKeys(selectedRowKeys);
      },
    };
  };

  const [registerTable, { reload, setSelectedRowKeys, getSelectRowKeys, getSelectRows }] = useTable(
    {
      title: '物料清单',
      api: getMaterialPageList,
      rowKey: 'id',
      columns,
      formConfig: {
        rowProps: {
          gutter: 16,
        },
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      showTableSetting: true,
      striped: false,
      actionColumn: {
        width: 120,
        title: t('操作'),
        dataIndex: 'action',
        slots: { customRender: 'action' },
      },
      rowSelection: {
        type: 'checkbox',
      },
      customRow,
    },
  );

  const handleCreate = () => {
    openModal(true, {
      isUpdate: false,
    });
  };

  const handleView = (record) => {
    isView.value = true;
    recordId.value = record.id;
  };

  const handleEdit = (record) => {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteMaterialList(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };

  const handleCheck = () => {
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要盘点的数据',
      });
      return false;
    }
    openStockModal(true, {
      id: getSelectRowKeys()[getSelectRowKeys().length - 1],
      type: 'check',
      baseInfo: getSelectRows()[getSelectRows().length - 1],
    });
  };

  const handleHistory = () => {
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要查询历史记录的数据',
      });
      return false;
    }
    openHistoryModal(true, {
      id: getSelectRowKeys()[getSelectRowKeys().length - 1],
    });
  };

  const handleScrap = () => {
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要报废的数据',
      });
      return false;
    }
    openStockModal(true, {
      id: getSelectRowKeys()[getSelectRowKeys().length - 1],
      type: 'scrap',
      baseInfo: getSelectRows()[getSelectRows().length - 1],
    });
  };

  const handleReload = () => {
    setSelectedRowKeys([]);
    reload();
  };

  const handleImport = () => {
    openImportModal(true, {
      title: t('快速导入'),
      api: downloadTemplate,
      templateTitle: '物料清单模板',
    });
  };
  const handleExport = async () => {
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要导出的数据',
      });
      return false;
    }
    const res = await exportInfo(getSelectRowKeys());
    downloadByData(
      res.data,
      '物料清单.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };
</script>
